import bcrypt from 'bcryptjs';
import crypto, { Cipher, Decipher } from 'crypto';
import { cryptconfig } from '../config/app.config';
/**
 * 加密方法
 * @param key  加密的key
 * @param iv   向量
 * @param data 需要加密的数据
 */
export function encrypt(data: string): string {
  let cipher: Cipher = crypto.createCipheriv(cryptconfig.algorithm, cryptconfig.key, cryptconfig.iv);
  let crypted: string = cipher.update(data, 'utf8', 'hex');
  crypted += cipher.final('hex');
  crypted = Buffer.from(crypted, 'hex').toString('base64');
  return crypted;
}

/**
 * 解密方法
 */
export function decrypt(data: string): string {
  let crypted: string = Buffer.from(data, 'base64').toString('hex');
  let decipher: Decipher = crypto.createDecipheriv(cryptconfig.algorithm, cryptconfig.key, cryptconfig.iv);
  let decode: string = decipher.update(crypted, 'hex', 'utf8');
  decode += decipher.final('utf8');
  return decode;
}

export class Bcrypt {
  hash(s: string) {
    const salt = bcrypt.genSaltSync();
    return bcrypt.hashSync(s, salt);
  }

  compare(s: string, hash: string) {
    return bcrypt.compareSync(s, hash);
  }

  getSalt(hash: string) {
    return bcrypt.getSalt(hash);
  }
}